package com.pro.springbootpro.security;

import com.pro.springbootpro.entity.SysRole;
import com.pro.springbootpro.entity.SysUser;
import com.pro.springbootpro.security.vo.SysUserDetails;
import com.pro.springbootpro.service.ISysRoleService;
import com.pro.springbootpro.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author DJR (1210843430@qq.com)
 * @version 1.0
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleService sysRoleService;

    /**
     * 根据用户名查用户信息
     *
     * @param username 用户名
     * @return 用户详细信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUser sysUser = sysUserService.selectByUserName(username);
        if (sysUser != null) {
            SysUserDetails sysUserDetails = new SysUserDetails();
            BeanUtils.copyProperties(sysUser, sysUserDetails);
            // 角色集合
            Set<GrantedAuthority> authorities = new HashSet<>();
            List<SysRole> roleList = sysRoleService.findRoleByUserId(sysUserDetails.getId());
            roleList.forEach(role -> {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
            });
            sysUserDetails.setAuthorities(authorities);
            return sysUserDetails;
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }
    }
}
